import React, { useState } from 'react';
import { ChevronDown, ChevronRight, File, Folder, FolderOpen, Image, Video, Music, FileText } from 'lucide-react';
import { FileTreeNode } from './types';
import { Badge } from '@/components/ui/badge';

interface ExpandableFileTreeProps {
  nodes: FileTreeNode[];
  level?: number;
}

const formatBytes = (bytes: number): string => {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

const getFileIcon = (node: FileTreeNode) => {
  if (node.isFolder) {
    return <Folder className="h-3.5 w-3.5 text-blue-500" />;
  }
  
  const extension = node.name.split('.').pop()?.toLowerCase();
  
  switch (node.mediaType) {
    case 1: // 图片
      return <Image className="h-3.5 w-3.5 text-green-500" />;
    case 3: // 视频
      return <Video className="h-3.5 w-3.5 text-red-500" />;
    case 2: // 音频
      return <Music className="h-3.5 w-3.5 text-purple-500" />;
    case 4: // 文档
      return <FileText className="h-3.5 w-3.5 text-orange-500" />;
    default:
      return <File className="h-3.5 w-3.5 text-gray-500" />;
  }
};

const getFileTypeColor = (node: FileTreeNode) => {
  if (node.isFolder) return 'bg-blue-50 text-blue-700 border-blue-200';
  
  switch (node.mediaType) {
    case 1: return 'bg-green-50 text-green-700 border-green-200';
    case 3: return 'bg-red-50 text-red-700 border-red-200';
    case 2: return 'bg-purple-50 text-purple-700 border-purple-200';
    case 4: return 'bg-orange-50 text-orange-700 border-orange-200';
    default: return 'bg-gray-50 text-gray-700 border-gray-200';
  }
};

const FileTreeItem: React.FC<{ node: FileTreeNode; level: number }> = ({ node, level }) => {
  const [isExpanded, setIsExpanded] = useState(false);
  const hasChildren = node.children && node.children.length > 0;
  const indent = level * 20;

  const toggleExpanded = () => {
    if (hasChildren) {
      setIsExpanded(!isExpanded);
    }
  };

  return (
    <div className="select-none">
      <div 
        className={`flex items-center gap-2 py-1.5 px-2 hover:bg-gray-100 cursor-pointer transition-colors ${
          node.isFolder ? 'font-medium' : ''
        }`}
        style={{ paddingLeft: `${8 + indent}px` }}
        onClick={toggleExpanded}
      >
        {/* 展开/收起图标 */}
        <div className="w-3 h-3 flex items-center justify-center flex-shrink-0">
          {hasChildren ? (
            isExpanded ? (
              <ChevronDown className="h-2.5 w-2.5 text-gray-500" />
            ) : (
              <ChevronRight className="h-2.5 w-2.5 text-gray-500" />
            )
          ) : (
            <div className="w-2.5 h-2.5" />
          )}
        </div>
        
        {/* 文件/文件夹图标 */}
        <div className="flex-shrink-0">
          {getFileIcon(node)}
        </div>
        
        {/* 文件名 */}
        <span className="flex-1 truncate text-sm min-w-0">
          {node.name}
        </span>
        
        {/* 文件大小和子项数量 */}
        <div className="flex items-center gap-1 flex-shrink-0">
          {!node.isFolder && (
            <Badge variant="outline" className={`text-xs px-1.5 py-0.5 ${getFileTypeColor(node)}`}>
              {formatBytes(node.size)}
            </Badge>
          )}
          
          {hasChildren && (
            <Badge variant="secondary" className="text-xs px-1.5 py-0.5">
              {node.children.length}
            </Badge>
          )}
        </div>
      </div>
      
      {/* 子项 */}
      {hasChildren && isExpanded && (
        <div className="border-l border-gray-200 ml-4">
          {node.children.map((child) => (
            <FileTreeItem key={child.id} node={child} level={level + 1} />
          ))}
        </div>
      )}
    </div>
  );
};

export const ExpandableFileTree: React.FC<ExpandableFileTreeProps> = ({ nodes, level = 0 }) => {
  if (!nodes || nodes.length === 0) {
    return (
      <div className="p-4 text-center text-gray-500 text-sm">
        暂无文件
      </div>
    );
  }

  return (
    <div className="w-full">
      {nodes.map((node) => (
        <FileTreeItem key={node.id} node={node} level={level} />
      ))}
    </div>
  );
};

export default ExpandableFileTree;